#!/usr/bin/perl -w

#####################################################################
# Program Variables - Go see the central config.pm!
#####################################################################
use FindBin qw($Bin);
use lib "$Bin";
use config;
use layout;

#####################################################################
# Program Modules
#####################################################################
# CGI Modules
use CGI;
use CGI::Carp;
use CGI::Pretty;

# Database Modules
use DBI;

# Data::Dumper for debugging
#use Data::Dumper;

# POSIX Stuff...
use POSIX;

#####################################################################
# Program Start
#####################################################################
my $cgi = new CGI;

my $pagetitle = &read_config_option("tank_name") . " Log/Notes";

# Web Page output
&ts_pagestart($pagetitle);

# Parameter List Checking
my %params = $cgi->Vars;

foreach $key (keys %params) {
    if ($key eq "View Full History") {
        &view_full_history();
    } elsif ($key eq "Add Log Entry") {
        my $time = sprintf "%04.4d-%02.2d-%02.2d %02.2d:%02.2d", $cgi->param('col_year'), $cgi->param('col_mon'), $cgi->param('col_mday'),
          $cgi->param('col_hour'), $cgi->param('col_min');
        $time ||= strftime "%Y-%m-%d %H:%M:%S", localtime;

        &write_results($time, $cgi->param('entry'));
    } elsif ($key =~ /delete_(.*)/i) {
        &delete_entry($1);
    }
}

#######################################
# Get the most recent statistics
my @recordlines;

my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");
my $sth = $dbh->prepare("SELECT * FROM notes ORDER BY collected DESC LIMIT 10;");

$sth->execute();
while (my $recref = $sth->fetchrow_hashref()) {
    my %record = %{$recref};

    my $timestamp = $record{collected};
    my $entry     = $record{note};
    $entry =~ s/\n/<br>/mg;

    push(
        @recordlines,
        $cgi->td([$timestamp])
          . $cgi->td(
            { -class => "left" },
            [ $entry, $cgi->submit(-name => "View Full History") . " " . $cgi->submit(-name => "delete_$timestamp", -label => "Delete Entry") ]));
}

# Close the database
$dbh->disconnect;
#######################################

print $cgi->center($cgi->p("Below is the last 10 Aquarium Notes/Log Entries, these help determine aquarium changes."));

my (undef, $min, $hour, $mday, $mon, $year, undef, undef, undef) = localtime(time);

$mon  += 1;       # Month in the range of 1-12
$year += 1900;    # Proper 4-digit year

# Start the forms
print $cgi->start_form;

#print $cgi->start_table({-align=>'center', -width=>"90%"});
print $cgi->start_table({ -align => 'center' });

print $cgi->Tr([ $cgi->th([ "Entry Date", "Entry Data", "&nbsp;" ]) ]);
print $cgi->Tr([@recordlines]);

print $cgi->Tr([
        $cgi->td(
            { -valign => "top" }, [
                $cgi->popup_menu(-name => "col_year", -default => $year, -values => [ 2012 .. 2020 ]) . "-"
                  . $cgi->popup_menu(-name => "col_mon",  -default => $mon,  -values => [ 1 .. 12 ]) . "-"
                  . $cgi->popup_menu(-name => "col_mday", -default => $mday, -values => [ 1 .. 31 ])
                  . $cgi->br . " at "
                  . $cgi->popup_menu(-name => "col_hour", -default => $hour, -values => [ 0 .. 23 ]) . ":"
                  . $cgi->popup_menu(-name => "col_min",  -default => $min,  -values => [ 0 .. 59 ]),
                $cgi->textarea(-name => "entry", -rows => "5", -cols => "50"),
                $cgi->submit(-name => "Add Log Entry") ]) ]);

print $cgi->end_table;
print $cgi->end_form;
print $cgi->p($cgi->center("Return to the " . $cgi->a({ -href => "./" }, &read_config_option("tank_name") . " Index") . " Page."));
print $cgi->end_html;
print "\n";
exit 0;

#####################################################################
# Program Subroutines
#####################################################################
sub view_full_history {
    my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");
    my $record_sth = $dbh->prepare_cached("SELECT * FROM notes ORDER BY collected DESC");

    print $cgi->start_table({ -align => 'center' });
    print $cgi->Tr([ $cgi->th([ "Date", "Entry" ]) ]);

    $record_sth->execute();
    while (my $recref = $record_sth->fetchrow_hashref()) {
        my %record = %{$recref};

        my $entry = $record{note};
        $entry =~ s/\n/<br>/mg;

        print $cgi->Tr([ $cgi->td({ -class => "left", -valign => "top" }, [ $record{collected}, $entry ]) ]);
    }

    print $cgi->end_table;
    print $cgi->center($cgi->p("Return to the " . $cgi->a({ -href => "notes.cgi" }, $pagetitle) . " Page."));
    print $cgi->end_html;
    print "\n";

    $dbh->disconnect;

    exit 0;
}

# Write out the given results
sub write_results {
    my $collected_time = shift @_;
    my $entry          = shift @_;

    my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");
    my $sth = $dbh->prepare_cached("INSERT INTO notes (collected, note) VALUES (datetime(?), ?)");

    $sth->execute($collected_time, $entry);

    # Close the database
    $dbh->disconnect;

    print $cgi->comment("Data Written"), "\n";
    $cgi->delete_all();
    return;
}

# Delete the result from the database
sub delete_entry {
    my $entry_time = shift @_;

    # Open the database
    my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");

    # Run the SQL to delete the entry
    $dbh->do("DELETE FROM notes WHERE collected=datetime(?)", undef, $entry_time);

    # Close the database
    $dbh->disconnect;

    print $cgi->comment("Entry Deleted"), "\n";
    $cgi->delete_all();
    return;
}

